<template>
<div class="layout">
	<Form ref="vform" :model="vform" :label-width="80"  :rules="ruleValidate">
		<Row type="flex" :gutter="16">
			<Col :span=17>
				<Row type="flex">
					<Col :span="24">
						<FormItem label="标题">
							<Input v-model="vform.title" placeholder="请填写标题"></Input>
						</FormItem>
						<FormItem label="关键字">
							<Input v-model="vform.keywords" placeholder="请填写关键字"></Input>
						</FormItem>
						<FormItem label="摘要">
							<Input v-model="vform.summary" placeholder="请填写摘要"></Input>
						</FormItem>
						<FormItem label="浏览数">
							<InputNumber :max="99999" :min="0" :step="1" v-model="vform.hits"></InputNumber>&nbsp;&nbsp;
							<label>浏览基数&nbsp;&nbsp;&nbsp;</label><InputNumber :max="99999" :min="0" :step="1" v-model="vform.hits_base"></InputNumber>&nbsp;&nbsp;
							<Checkbox v-model="can_comment">开启评论</Checkbox>
							<Checkbox v-model="is_visibility">隐藏文章</Checkbox>
							<Checkbox v-model="is_url">链接文章</Checkbox>
							<Checkbox v-model="isrecommend">推荐</Checkbox>
							<Checkbox v-model="istop">置顶</Checkbox>
						</FormItem>
					
						<FormItem label="文章链接" v-if="1==vform.is_url">
							<Input v-model="vform.url" placeholder="请填写文章链接"></Input>
						</FormItem>

						<FormItem label="主要经历" v-if="0==vform.is_url">
							<quill-editor ref="quill1" v-model="vform.content" :options="editorOption"></quill-editor>
						</FormItem>
					</Col>
				</Row>
			</Col>
			<Col :span=7>
				<Card >
					<p slot="title">
						<Icon type="ios-film-outline"></Icon>
						文章控制
					</p>

					<div style="padding-left:10px;padding-right:10px;padding-bottom:10px">
						<FormItem label="状态">
							<Select v-model="vform.status" >
								<Option v-for="(item,index) in statusList" :value="item.value" :key="index">{{ item.label }}</Option>
							</Select>
						</FormItem>
						<FormItem label="栏目">
							<Select v-model="vform.channel_id" >
								<Option v-for="(item,index) in channelList" :value="item.value" :key="index">{{ item.label }}</Option>
							</Select>
						</FormItem>
						<FormItem label="来源">
							<Input v-model="vform.source" placeholder="请填写来源"></Input>
						</FormItem>
						<FormItem label="作者">
							<Input v-model="vform.author" placeholder="请填写作者"></Input>
						</FormItem>
						<FormItem label="发布时间">
							<DatePicker @on-change="changeDate" :value="vform.publish_at" type="date" show-week-numbers placement="bottom-end" placeholder="请选择出生年月"></DatePicker>
						</FormItem>
						<FormItem label="权重">
							<InputNumber :max="99999" :min="0" :step="1" v-model="vform.order"></InputNumber>
						</FormItem>
						
						<Button type="success" @click="save">保存</Button>
					</div>
				</Card>
				<div class="cleaner10"></div>
				<Card class="thumbnail-wrapper">
					<p slot="title">
						<Icon type="ios-film-outline"></Icon>
						封面
					</p>
					<div class="btn-thumbnail" @click="getPictures(0)" v-show="''==vform.thumbnail"><Icon type="md-add" :size="40"></Icon></div>
					<div class="img-wrapper" v-show="''!=vform.thumbnail" :style="{backgroundImage:'url('+vform.thumbnail+')'}"></div>

					<div class="upload-list-cover" v-show="''!=vform.thumbnail">
						<Icon type="ios-eye-outline" size="40"  @click.native="onView(vform.thumbnail)"></Icon>
						<Icon type="ios-trash-outline" size="36" @click.native="onRemove"></Icon>
					</div>
				</Card>
			</Col>

		</Row>
	</Form>



	<Button type="text" @click="getPictures(1)" id="btnShowPictureBox"></Button>
	<Picture-Selector :show.sync="showPictureBox" @on-hide="showPictureBox=false" @on-change="insertImage"></Picture-Selector>
	
    <Modal title="查看图片" v-model="currentImagvisible">
        <img :src="currentImag" v-if="currentImagvisible" style="width: 100%">
    </Modal>
</div>
</template>
<script>
// 引入子组件
import hljs from 'highlight.js'
import 'highlight.js/styles/vs2015.css'

// quill编辑器的字体
var fonts = ['SimSun', 'Microsoft-YaHei','Arial','Times-New-Roman','sans-serif'];  
var Font = Quill.import('formats/font'); 
Font.whitelist = fonts; //将字体加入到白名单 
Quill.register(Font, true);

import PictureSelector from '@/components/PictureSelector/PictureSelector.vue'
import {mapState,mapGetters} from 'vuex'
import {Tag, Card, Page, Modal, Spin, Row, Col, ButtonGroup, Button,  Breadcrumb, BreadcrumbItem, Icon, Form, FormItem, Input, Select, Option, DatePicker, InputNumber } from 'iview';
export default { 
	name:'article-view',
	components: {Tag, Card, Page, Modal, PictureSelector, Spin, Row, Col, ButtonGroup, Button, Breadcrumb, BreadcrumbItem, Icon, Form, FormItem, Input, Select, Option, DatePicker, InputNumber},
	data () {
		return {
			title:'编辑',
			tabIndex:'name1',
			showPictureBox:false,
			spinShow:true,
			currentImag:'',
			currentImagvisible:false,
			editorIndex:0,
			editorOption:{
				placeholder:'请输入内容',
				modules:{
					imageResize: {},
					toolbar:{
                        container: [
							['bold', 'italic', 'underline', 'strike'],        // toggled buttons
							['blockquote', 'code-block'],           // custom button values
							[{ 'list': 'ordered'}, { 'list': 'bullet' }],
							[{ 'script': 'sub'}, { 'script': 'super' }],      // superscript/subscript
							[{ 'indent': '-1'}, { 'indent': '+1' }],          // outdent/indent
							['link'],
							[{ 'size': ['small', false, 'large', 'huge'] }],  // custom dropdown
							[{ 'header': [1, 2, 3, 4, 5, 6, false] }],

							[{ 'color': [] }, { 'background': [] }],          // dropdown with defaults from theme
							[{ 'font': fonts }],
							[{ 'align': [] }],
							['clean'],
                            ['vimage'],   
                        ],
                        handlers: {'vimage': function() {document.getElementById("btnShowPictureBox").click()}}
                    },
					syntax: {highlight:text => hljs.highlightAuto(text).value},


				}
			},
			ruleValidate: {
				name: [
					{ required: true, message: '请填写姓名', trigger: 'blur' }
				],
				code: [
					{ required: true, message: '请填写代码', trigger: 'blur' }
				],
				status: [
					{ required: true, message: '请选择状态', trigger: 'change' }
				],
				sequence: [
					{ required: true, type:'number', message: '请填写权重', trigger: 'change' }
				],
			},
			vform:{
				is_url:0,
				thumbnail:'',
				flag:0
			},
			vSummaryForm:{
				id:0,
				code:'',
				experience:'',
				timerange:'',
				achievement:'',
				images:[]
			},
			
			statusList: [
				{value: "0",label: '暂存'},
				{value: "1",label: '发布'},
			],
			
			channelList: [
				{value: "100",label: '公司动态'},
				{value: "101",label: '行业动态'},
				{value: "102",label: '使用帮助'},
				{value: "103",label: '日常问题'},
				{value: "104",label: '期货专栏'},
				{value: "105",label: '新闻资讯'},
			],
		}
	},
	methods:{
		init:function(){
			let self=this
			self.$store.dispatch("setSpinShow",true)

			function action1(){return self.$http.get("/v1/cms/articles/"+self.$route.params.id,{params: { 'token': self.token }})}
			
			self.$http.all([action1()])
			.then(self.$http.spread(function (response1){
				if(200==response1.data.status && 0==response1.data.code)
				{
					response1.data.data.hits=parseInt(response1.data.data.hits)
					response1.data.data.hits_base=parseInt(response1.data.data.hits_base)
					response1.data.data.order=parseInt(response1.data.data.order)
					
					self.vform=response1.data.data
				}else{self.$Message.error(response1.data.message)}
				
				self.$store.dispatch("setSpinShow",false)
			})).catch(self.$http.spread(function (error1) { 
				// self.$Message.error(error1)
				self.$store.dispatch("setSpinShow",false)
			}))
		},
		changeMenu:function(nid){
			let _index = 0
			this.menuIndex.forEach(item=>{
				if(nid==item.nid){
					_index=item.id
				}
			})
			this.$store.dispatch('setMenuActive',_index+'')
			this.$store.dispatch('setMenuOpen', [_index+''])
			return false;
		},
		changeDate:function(val, obj){
			this.vform.publish_at=val
		},
		
		changeStatus:function(uid,statusId){
			let self=this
			self.tableLoading=true
			self.$http.post("/v1/cms/articles?_method=put&token="+self.token,{'id':uid,'data':'{"status":"'+parseInt(statusId)+'"}'})
			.then(function(response){
				if(200==response.data.status && 0==response.data.code)
				{
					self.vform.status=statusId
					self.$Message.success('操作成功');
				}else{
					
					self.$Message.error(response.data.message);
				}
				self.tableLoading=false
			}).catch(function(error){
				self.$Message.error( error.message);
				self.tableLoading=false
			})
		},
		save:function(){
			let self=this
			self.$store.dispatch("setSpinShow",true)
			self.$http.post("/v1/cms/articles?token="+self.token,{'id':self.$route.params.id,'data':JSON.stringify(self.vform)})
			.then(function(response){
				if(200==response.data.status && 0==response.data.code)
				{
					self.$router.push({path:'/cms/article/edit/'+response.data.data.id})
					self.$Message.success('操作成功');
				}else{
					self.$Message.error(response.data.message);
				}
				self.$store.dispatch("setSpinShow",false)
			}).catch(function(error){
				self.$Message.error(error.message);
				self.$store.dispatch("setSpinShow",false)
			})
		},
		getPictures:function(index){
			this.editorIndex=index
			this.showPictureBox=true
		},
		insertImage:function(url){
			if(1==this.editorIndex){
				// 获取富文本组件实例
				let quill = this.$refs.quill1.quill
				quill.focus()
				// 获取光标所在位置
				let length = quill.getSelection().index;
				// 插入图片  res.info为服务器返回的图片地址
				quill.insertEmbed(length, 'image', url)
				// 调整光标到最后
				quill.setSelection(length + 1)
				this.showPictureBox=false
			}else{
				this.vform.thumbnail=url
				this.showPictureBox=false
			}
		},
		onRemove:function(){this.vform.thumbnail=''},
		onView:function(url){
			this.currentImag=url
			this.currentImagvisible=true
		}
	},
	created:function(){
	},
	mounted () {
		// this.init()
    	this.setTitle(this.title)
	},
	activated:function(){
	},
	computed:{
		...mapGetters(['token','menuIndex'])
		,can_comment:{
			get(){return 1==this.vform.can_comment?true:false},
			set(val){if(val){this.vform.can_comment=1}else{this.vform.can_comment=0} }
		}
		,is_visibility:{
			get(){return 1==this.vform.is_visibility?true:false},
			set(val){if(val){this.vform.is_visibility=1}else{this.vform.is_visibility=0} }
		}
		,is_url:{
			get(){return 1==this.vform.is_url?true:false},
			set(val){if(val){this.vform.is_url=1}else{this.vform.is_url=0} }
		}
		,isrecommend:{
			get(){
				if(1==this.vform.flag){return true}
				return false
			},
			set(val){if(val){this.vform.flag=1}else{this.vform.flag=0} }
		}
		,istop:{
			get(){
				if(2==this.vform.flag){return true}
				return false
			},
			set(val){if(val){this.vform.flag=2}else{this.vform.flag=0} }
		}
	},
}



</script>
<style lang="less" scoped>


.thumbnail-wrapper{
	margin-bottom:15px;padding:5px;
	
	.btn-thumbnail{text-align: center;border: 1px dashed #eee;height: 100px;line-height: 100px;}
	.btn-thumbnail:hover{
		border: 1px dashed #5cadff;
		i{color:#5cadff;}
	}

	.upload-list-cover{
        display: none;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
		background: rgba(0,0,0,.5);
		text-align: center;
		i{
			color: #fff;
			font-size: 20px;
			cursor: pointer;
			margin: 0 2px;
			position:relative;
			top:35%;
		}
	}

	.img-wrapper{height:180px;background-size: cover;}
}
.thumbnail-wrapper:hover .upload-list-cover{
        display: block;
}
</style>